import { openDB } from "idb"

const DB_NAME = "SurveyDB"
const STORE_NAME = "surveys"

export async function getDb() {
  return openDB(DB_NAME, 1, {
    upgrade(db) {
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, { keyPath: "id" })
      }
    }
  })
}

export async function saveSurvey(data: any) {
  // console.log('保存的数据', data);
  const db = await getDb()
  await db.put(STORE_NAME, { ...data, updatedAt: Date.now() })
}

export async function getSurveyById(id: string) {
  const db = await getDb()
  return db.get(STORE_NAME, id)
}

export async function getSurveys() {
  const db = await getDb()
  return db.getAll(STORE_NAME)
}

export async function deleteSurvey(id: string) {
  const db = await getDb()
  await db.delete(STORE_NAME, id)
}
